package pub.cleangao.codegen.util;

import com.jfinal.template.Engine;
import pub.cleangao.common.util.Resources;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;


/**
 * jfinal-enjoy 引擎
 */
public class EnjoyEngine {

    private static final Engine engine = Engine.create("template-assembler");


    public static String assemble(String resourceTemplatePath, Map<String, Object> context) {
        try (InputStream inputStream = Resources.getResourceAsStream(resourceTemplatePath)) {
            ByteArrayOutputStream template = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                template.write(buffer, 0, length);
            }
            return engine.getTemplateByString(template.toString(StandardCharsets.UTF_8)).renderToStringBuilder(context).toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
